package com.bdqn.Practice.controller;

import com.bdqn.Practice.pojo.Supplier;
import com.bdqn.Practice.pojo.SysUser;
import com.bdqn.Practice.service.SupplierService;
import com.bdqn.Practice.util.Constants;
import com.bdqn.Practice.util.Page;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/supplier")
public class SupplierMapperController {
    Logger logger=Logger.getLogger(SupplierMapperController.class);
    @Resource
    private SupplierService supplierService;
    @GetMapping(value = "list")
    public String userList(Model model, @RequestParam(defaultValue = "1") Integer pageIndex, String queryRealName, String queryRoleId ){
        Page page=new Page();
        page.setTotalCount(supplierService.count());
        page.setCurrentPageNo(pageIndex);
        page.setList(supplierService.selectPageList(page.getCurrentPageNo(),page.getPageSize(),queryRealName,queryRoleId));

        model.addAttribute("supplierList",page.getList());
        model.addAttribute("page",page);
        return "supplier/list";
    }

    @GetMapping(value = "toUpdate/{id}")
    public String toUpdate(Model model,Integer supId){

        return "supplier/update";
    }

    @GetMapping(value = "toAdd")
    public String toAdd(){

        return "supplier/add";
    }

    @PostMapping(value = "add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request, @RequestParam MultipartFile [] attachs){
        String companyLicPicPath=null;
        String orgCodePicPath=null;
        String error=null;
        boolean flag=true;
        String uploadPath=session.getServletContext().getRealPath(Constants.UPLOAD_PATH);
        logger.debug("文件上传的路径:"+uploadPath);
        for (int i=0;i<attachs.length;i++){
            MultipartFile attach=attachs[i];
            if (!attach.isEmpty()){
                if (i==0){
                    error="uploadFileError";
                }else{
                    error="uploadOcError";
                }
                String oldFileName=attach.getOriginalFilename();//原文件名字

                String prefix= FilenameUtils.getExtension(oldFileName);//后缀
                if (attach.getSize()> Constants.maxUploadSize){
                    System.out.println(500);
                    request.setAttribute(error,"*上传大小不得超过500KB");
                    flag=false;
                }else if (prefix.equalsIgnoreCase("jpg")
                        ||prefix.equalsIgnoreCase("png")
                        ||prefix.equalsIgnoreCase("jpeg")
                        ||prefix.equalsIgnoreCase("pneg")){
                    String fileName=System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
                    File target =new File(uploadPath);

                    if (!target.exists()){
                        System.out.println("新建文件夹");
                        target.mkdir();
                    }
                    try {
                        attach.transferTo(new File(target,fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        request.setAttribute(error,"*上传失败");
                        flag=false;
                    }
                    if (i==0){
                        companyLicPicPath=File.separator+Constants.UPLOAD_PATH+File.separator+fileName;
                    }else if (i==1){
                        orgCodePicPath=File.separator+Constants.UPLOAD_PATH+File.separator+fileName;
                    }
                }else{
                    request.setAttribute(error,"*上传图片格式不正确");
                    flag=false;
                }
            }
        }
        if (flag){
            supplier.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanyLicPicPath(companyLicPicPath);
            supplier.setOrgCodePicPath(orgCodePicPath);
            if (supplierService.add(supplier)>0){
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }

    public String uploadFiles(String uploadPath, HttpServletRequest request,@RequestParam MultipartFile [] attachs ){


        return uploadPath;
    }

    @GetMapping("view/{id}")
    public String view(@PathVariable Integer id,Model model){
        Supplier supplier=supplierService.supplierView(id);
        model.addAttribute("supplier",supplier);
        return "supplier/view";
    }

}
